package cn.crawler.framework.filter.bize;

import cn.crawler.framework.base.exceptions.BizException;
import cn.crawler.framework.base.model.enums.BizExceptionEnum;
import cn.crawler.framework.util.Result;
import cn.crawler.framework.util.TLManager;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class BizExceptionFilter implements Filter {

    private static final Log log = Logs.get();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse res2 = (HttpServletResponse) servletResponse;
        try {
            filterChain.doFilter(servletRequest, servletResponse);
            //error来自actionContext,set于NutFilterProcessor
            Throwable error = TLManager.getError();
            TLManager.close();
            if (error != null) {
                throw error;
            }
        } catch (BizException e) {
            Result.error(res2, e.getRemand());
        } catch (Exception e1) {
            String content = e1.toString();
            if (content.contains("cn.crawler.framework.base.exceptions.BizException")) {
                String substring = content.substring(content.indexOf("{remand='") + 9, content.indexOf("'}"));
                BizExceptionEnum bize = BizExceptionEnum.getByCode(substring);
                Result.error(res2, bize == null ? substring : bize.getCode());
            } else {
                Result.error(res2, null, e1.toString());
            }
        } catch (Throwable throwable) {
            log.error(throwable.getMessage());
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
